﻿using System;
using System.Windows.Forms;
using CSLauncher.Hotkey;
using CSLauncher.Hotkey.Interface;

namespace CSLauncher
{
    static class Program
    {
        private static CSForm csForm;
        private static CSTrayIcon csTrayIcon;

        public static IHotkeyManager HotkeyManager { get; private set; }
        
        public static void ChangeHotkey(HotkeyData newHotkey)
        {
            try
            {
                HotkeyManager.Register(0, newHotkey);
                csTrayIcon.Icon.ShowBalloonTip(0, "CSLauncher", string.Format("Press {0} to launch the menu", newHotkey), ToolTipIcon.Info);
            }
            catch (HotkeyRegistrationFailedException)
            {
                MessageBox.Show(
                    string.Format(
                        "Unable to registry the hotkey {0}.\nThe menu can only be launched using the tray icon",
                        newHotkey),
                    "CSLauncher",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                csTrayIcon.Icon.ShowBalloonTip(0, "CSLauncher", string.Format("Double click this icon to launch the menu"), ToolTipIcon.Info);
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            csTrayIcon = new CSTrayIcon();
            
            csTrayIcon.Icon.DoubleClick += delegate { LaunchMenu(); };

            HotkeyManager = new WindowsHotkeyManager();
            HotkeyManager.HotkeyPressed += HotkeyPressed;

            ChangeHotkey(Properties.Settings.Default.Hotkey);
            
            Application.Run();

            csTrayIcon.Dispose();
        }

        static void LaunchMenu()
        {
            if (csForm != null)
            {
                return;
            }
            try
            {
                csForm = new CSForm();
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Unable to launch the menu: {0}", e.Message), "CSLauncher",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            csForm.ShowDialog();
            csForm.Dispose();
            csForm = null;
        }

        static void HotkeyPressed(object sender, HotkeyPressedEvent e)
        {
            if (e.Identifer == 0)
            {
                LaunchMenu();
            }
        }
    }
}
